<!--
  * SQL 预览代码
  *
  * @Author:    KeissCake
  * @Date:
  * @Wechat:
  * @Email:
  * @Copyright
-->
<template>
  <a-drawer
      title="SQL代码预览"
      :open="visibleFlag"
      :width="1200"
      :footerStyle="{ textAlign: 'right' }"
      :bodyStyle="{ padding: '8px 24px' }"
      @close="onClose"
      :maskClosable="false"
      :destroyOnClose="true"
  >
    <a-row justify="space-between" class="smart-margin-bottom11">
      <a-radio-group v-model:value="languageType" button-style="solid" @change="onChangeLanguageType">
        <a-radio-button :value="LANGUAGE_LIST[0]">Souce端代码</a-radio-button>
        <a-radio-button :value="LANGUAGE_LIST[1]">Sink端代码</a-radio-button>
      </a-radio-group>
    </a-row>
    <a-tabs v-model:activeKey="fileKey" size="small" @change="onChangeTab">
      <a-tab-pane v-for="item in tabList" :key="item" :tab="item" />
    </a-tabs>
    <div>
      <pre><code :class="codeClass">{{resultCode}}</code></pre>
    </div>
  </a-drawer>

</template>

<script setup>
import { computed, nextTick, ref } from 'vue';
import {
  LANGUAGE_LIST,
  SOUCE_FILE_LIST, SINK_FILE_LIST
} from '../../datatask-sql-util.js';
import { smartSentry } from '/src/lib/smart-sentry';
import { lineNumbersBlock } from '/src/lib/highlight-line-number';
import hljs from 'highlight.js';
import 'highlight.js/styles/github-dark.css';
import sql from 'highlight.js/lib/languages/sql'
import { message } from 'ant-design-vue';
import {datataskApi} from "/src/api/business/super-computer/datatask/datatask-api.js";

// ------------------ 显示，关闭 ------------------

// 显示
const visibleFlag = ref(false);
let taskId = ref(null)
async function showModal(record) {
  //判断启用
  if (record.enabledFlag === 0) {
    message.error("当前任务未启用")
    return;
  }
  //表名用处存疑
  // tableName.value = tableInfo.tableName;
  // tableComment.value = tableInfo.tableComment;
  let type
  await datataskApi.getSourceType(record.dataSourceId).then(result => {
    type = String(result.data).toUpperCase();
  })
  if (!(type==="MYSQL")){
    message.error("数据源非MySQL,无代码")
    return;
  }
  visibleFlag.value = true;
  //写一个方法获取数据源类型
  taskId.value = record.taskId;
  nextTick(() => {
    onChangeTab(fileKey.value);
  });
}

// 关闭
function onClose() {
  visibleFlag.value = false;
}

/*// ------------------ 表------------------
const tableName = ref('');
const tableComment = ref('');*/

// ------------------ 标签页 ------------------
//默认Souce端
const languageType = ref(LANGUAGE_LIST[0]);
const tabList = computed(() => {
  if (languageType.value === LANGUAGE_LIST[0]) {
    return SOUCE_FILE_LIST;
  } else {
    return SINK_FILE_LIST;
  }
});

const fileKey = ref(tabList.value[0]);

function getLanguage() {
  if (languageType.value === LANGUAGE_LIST[0] || languageType.value === LANGUAGE_LIST[1]) {
    return 'sql';//两种模版本质都是sql
  } else {
    return '待补充新类型';
  }
}
//改变标签时给语言类型赋值
function onChangeLanguageType(e) {
  if (e.target.value === LANGUAGE_LIST[0]) {
    fileKey.value = SOUCE_FILE_LIST[0];
  } else if (e.target.value === LANGUAGE_LIST[1]) {
    fileKey.value = SINK_FILE_LIST[0];
  }
  //触发选项卡改变
  onChangeTab(fileKey.value);
}


// ------------------ 查询代码 ------------------
const codeClass = ref('language-sql');

function onChangeTab(tab) {
  //清空resultCode
  resultCode.value = '';
  //模版文件
  let templateFile = tab;
  let language = getLanguage();
  //代码高亮(选择语言sql)
  hljs.registerLanguage(language, sql);
  codeClass.value = 'language-' + language;
  let type = tab
  console.log('当前选择的模版'+templateFile);
  nextTick(() => {
    generateCode(taskId.value,type);
  });
}

const resultCode = ref('');
async function generateCode(taskId,type) {
  try {
    //获得代码
    let result = await datataskApi.preview(taskId);
    if (type==="sink.sql"){
      resultCode.value = result.data.sink;
    }else{
      resultCode.value = result.data.source;
    }

    nextTick(() => {
      document.querySelectorAll('pre code').forEach((block) => {
        block.setAttribute('highlighted', 'true');
        hljs.highlightElement(block);
        lineNumbersBlock(block);
        block.innerHTML =
            "<div><div style='padding: 5px 0px 10px 20px;float:right'><span style='margin-right: 10px;padding: 5px;border: white solid 1px;color:white;border-radius: 2px'>" +
            block.className.match(/(?<=language-).*(?= hljs)/).toString() +
            "</span><button class='ant-btn ant-btn-sm' >复制代码</button></div>" +
            block.innerHTML +
            '</div>';
        let copyButton = block.querySelector('button');
        if (copyButton != null) {
          copyButton.onclick = function () {
            copy(resultCode.value);
            message.success('复制成功！');
          };
        }
      });
    });
  } catch (e) {
    smartSentry.captureError(e);
  }
}

function copy(value) {
  let textarea = document.createElement('textarea');
  document.body.appendChild(textarea);
  textarea.value = value;
  textarea.select();
  document.execCommand('Copy');
  document.body.removeChild(textarea);
}

defineExpose({
  showModal,
});
</script>

<style lang="less" scoped>
.preview-title {
  font-weight: 600;
  margin: 5px 0px;
}

.preview-block {
  font-size: 12px;
  background-color: #f9f9f9;
  padding: 10px 5px;
}

:deep(.hljs) {
  .hljs-ln-numbers {
    text-align: center;
    color: #ccc;
    border-right: 1px solid #ccc;
    vertical-align: top;
    padding-right: 5px !important;
  }

  .hljs-ln-code {
    padding-left: 5px !important;
  }
}
</style>
